import {
  ScoreSubmitParamData,
  scoreBySelfTemporarySave,
  selectPmData,
  scoreByLeaderSubmit,
  AnnexData
} from '@/api/myPerformance'
import {CCard} from '@/components/card'
import {TargetWeight} from '@/components/input/targetWeight'
import ScoreSummarizeModal from '@/components/modal/scoreSummarizeModal'
import {PMContent, PMLayout, PMNav} from '@/components/others/layout'
import {SplitLine} from '@/components/splitLine'
import {CnBoldSpan, CnMediumP, CnNormalP} from '@/components/text'
import useModal from '@/hooks/modalHook'
import {useRouteQuery} from '@/hooks/pageRedirect'
import useMyPm from '@/hooks/pm/myPm'
import useOwner from '@/hooks/pm/owner'
import useProgress from '@/hooks/pm/progress'
import {useTableLoading} from '@/hooks/tableHook'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {ant_design_vue} from '@/libs/global/antDesignVue'
import {SelfScoreQuery} from '@/libs/pageRedirect'
import {unReplaceBreak, replaceBreak, zeroize, checkValueIsInRange, numRound} from '@/libs/toolkit'
import {ddGetAuth, ddUploadFile} from '@/api/dd'
import deepClone from '@/libs/deepClone'
import {defineComponent, reactive, computed, onMounted} from 'vue'

const {message} = ant_design_vue
interface CustomPmTarget extends MyPm.PmTarget {
  score: number | undefined
  scoreContent: string
  scoreDesc: string
}

interface CustomPmData extends Omit<MyPm.PmData, 'pmTargetList'> {
  pmTargetList: CustomPmTarget[]
}

export default defineComponent({
  name: 'scoreBySelf',
  setup(props, ctx) {
    const {getQueryData, router} = useRouteQuery({
      queryKeys: ['defaultPmId']
    })
    const queryData = getQueryData<SelfScoreQuery>()
    if (!queryData) {
      router.back()
      return () => (
        <PMLayout>
          <PMNav></PMNav>
          <PMContent></PMContent>
        </PMLayout>
      )
    }
    const {defaultPmId} = queryData

    const {store} = useGlobalAPI()

    const {loading, startLoading, closeLoading} = useTableLoading()

    const {
      scoreSelfByLoginUser,
      loginUser,
      allScoreSelf,
      scoreLeaderByLoginUser,
      appointByLoginUser,
      getPmProgress,
      nowRunning,
      nowRunningByLoginuser
    } = useProgress({
      pmId: defaultPmId
    })

    const {pm, getPmByPmId, setPm, myPmList} = useMyPm()

    const {owner, udpateOwner} = useOwner()

    const {
      visible: scoreSummarizeVisible,
      openModal: openScoreSummarizeModel,
      closeModal: closeScoreSummarize
    } = useModal()

    let state = reactive<{
      /**当前绩效的维度列表 */
      pmDataList: CustomPmData[]

      /**评分总结 */
      summarize: string

      /**附件 */
      fileList: {
        uid: string // 文件唯一标识，建议设置为负数，防止和内部产生的 id 冲突
        name: string // 文件名
        status: 'uploading' | 'done' | 'error' | 'removed' // 状态有：uploading done error removed
      }[]
      /**已上传附件 */
      annexDataList: AnnexData[]
    }>({
      pmDataList: [],
      summarize: '',
      annexDataList: [],
      fileList: []
    })

    /**表格头 */
    const tableColumns = computed<CColumn<CustomPmTarget>[]>(() => {
      let columns: CColumn<CustomPmTarget>[] = [
        {
          title: '指标名称',
          dataIndex: 'pmTargetName',
          ellipsis: true,
          width: 'auto'
        },
        {
          title: '权重(%)',
          dataIndex: 'pmTargetWeight',
          width: 80,
          align: 'center',
          ellipsis: true
        },
        {
          title: '考核标准',
          dataIndex: 'pmTargetStand',
          ellipsis: true,
          minWidth: 120
        }
      ]

      // 根据自评人数，动态添加自评栏
      const selfCheckColumns: CColumn<CustomPmTarget>[] = allScoreSelf.value.map((item, idx) => ({
        title: `自评(${item.makeUserName})`,
        children: [
          {
            title: '评分',
            dataIndex: ['scoreSelfCheckList', idx + '', 'score'],
            align: 'center',
            width: 80,
            ellipsis: true
          },
          {
            title: '评分说明',
            dataIndex: ['scoreSelfCheckList', idx + '', 'scoreContent'],
            align: 'center',
            width: 180,
            ellipsis: true
          }
        ]
      }))
      columns.push(...selfCheckColumns)

      if (scoreLeaderByLoginUser.value) {
        const leaderCheckColumns: CColumn<CustomPmTarget>[] = [
          {
            title: `主管-${scoreLeaderByLoginUser.value.makeUserName}(${scoreLeaderByLoginUser.value.scoreWeight}%)`,
            dataIndex: 'score',
            align: 'center',
            width: 160,
            ellipsis: true
          },
          {
            title: `评分说明`,
            dataIndex: 'scoreContent',
            align: 'center',
            width: 180,
            ellipsis: true
          }
        ]

        columns.push(...leaderCheckColumns)
      } else if (appointByLoginUser.value) {
        const appointColumns: CColumn<CustomPmTarget>[] = [
          {
            title: `指定人员评分-${appointByLoginUser.value.makeUserName}(${appointByLoginUser.value.scoreWeight}%)`,
            dataIndex: 'score',
            align: 'center',
            width: 160,
            ellipsis: true
          },
          {
            title: `评分说明`,
            dataIndex: 'scoreContent',
            align: 'center',
            width: 180,
            ellipsis: true
          }
        ]

        columns.push(...appointColumns)
      }

      console.log('主管评分表格头', columns)

      return columns
    })

    const scoreCount = computed(() => {
      console.log(scoreLeaderByLoginUser.value)
      let num = (eval(
        (state.pmDataList || [])
          .map(item =>
            item.pmTargetList.map(target => {
              if (target.isBonus === 0) {
                return (
                  (target.score || 0) *
                  (target.pmTargetWeight / 100) *
                  ((scoreLeaderByLoginUser.value === undefined
                    ? 100
                    : scoreLeaderByLoginUser.value.scoreWeight) /
                    100)
                )
              } else {
                return target.score || 0
              }
            })
          )
          .flat(Infinity)
          .join('+')
      ) || 0) as number

      let returnData = zeroize(num, 2, true)

      return returnData
    })

    function getTableData() {
      startLoading()
      /**获取个人绩效中的维度及指标数据 */
      selectPmData({pmId: Number(defaultPmId)})
        .then(res => {
          if (res.data && res.data.length === 0) {
            state.pmDataList = []
          } else {
            res.data.sort((a, b) => a.sort - b.sort)
            let pmDataList: CustomPmData[] = res.data.map<CustomPmData>(item => ({
              pmId: item.pmId,
              pmDimensionId: item.pmDimensionId,
              pmDimensionName: item.pmDimensionName,
              pmDimensionTypeCode: item.pmDimensionTypeCode,
              pmDimensionWeight: item.pmDimensionWeight,
              isCustomSelf: item.isCustomSelf,
              isImport: item.isImport,
              sort: item.sort,
              pmTargetList: item.pmTargetList
                .filter(item => {
                  /**当前登陆者不是该绩效所属人时 */
                  // 当前登陆者是主管评分人,且目标评分人有人时
                  if (scoreLeaderByLoginUser.value && item.appointUserDDId) {
                    return false
                  } else if (
                    appointByLoginUser.value &&
                    item.appointUserDDId !== appointByLoginUser.value.makeUserDDId
                  ) {
                    // 当前登陆者是目标指定评分人,且该目标的指定评分人不是当前登陆者时
                    return false
                  } else {
                    // 都不是的时候，当前登陆者就是管理员
                    return true
                  }
                })
                .map<CustomPmTarget>(target => {
                  let scoreLeader = target.leaderCheckList?.find(
                    item => item && item.makeUserDDId === loginUser.value.userId
                  )
                  return {
                    isBonus: target.isBonus,
                    pmTargetRange: target.pmTargetRange,
                    appointScoreSign: target.appointScoreSign,
                    appointUserDDId: target.appointUserDDId,
                    makeProperty: undefined,
                    pmTargetId: target.pmTargetId,
                    pmDimensionId: target.pmDimensionId,
                    pmTargetName: target.pmTargetName,
                    pmTargetStand: target.pmTargetStand,
                    pmTargetWeight: target.pmTargetWeight,
                    sort: target.sort,
                    score: scoreLeader ? scoreLeader.score : undefined,
                    scoreContent: '',
                    scoreDesc: '',
                    scoreSelfCheckList: target.scoreSelfCheckList,
                    leaderCheckList: target.leaderCheckList,
                    appointCheckList: target.appointCheckList,
                    isMustSelect: target.isMustSelect
                  }
                })
            }))

            console.log(pmDataList)
            // 给每个维度添加一个总分项
            for (let i = 0; i < pmDataList.length; i++) {
              const pmData = pmDataList[i]
              let pmTargetList = pmData.pmTargetList

              // 根据自评人数创建新的的自评列表
              let coustomScoreSelfCheckList: MyPm.ScoreSelfCheck[] = allScoreSelf.value.map(
                item => ({
                  pmTargetCheckId: -1,
                  makeUserDDId: item.makeUserDDId,
                  makeUserName: item.makeUserName,
                  pmTargetId: -1,
                  pmProgressId: item.pmProgressId,
                  score: 0,
                  scoreContent: '',
                  scoreDesc: '',
                  scoreWeight: item.scoreWeight
                })
              )

              // 给默认的自评列表填充自评人的评分
              for (let j = 0; j < pmTargetList.length; j++) {
                const pmTarget = pmTargetList[j]

                let scoreSelfCheckList = pmTarget.scoreSelfCheckList || []

                for (let k = 0; k < scoreSelfCheckList.length; k++) {
                  const scoreSelfCheck = scoreSelfCheckList[k]

                  coustomScoreSelfCheckList[k].score +=
                    (scoreSelfCheck.score * pmTarget.pmTargetWeight) / 100
                }
              }

              // 当前维度所有指标权重
              let pmTargetWeightCount = eval(
                pmData.pmTargetList
                  .map(target => target.pmTargetWeight)
                  .flat(Infinity)
                  .join('+')
              ) as number

              // 将新的自评列表加入总分项中
              pmTargetList.push({
                isBonus: 0,
                pmTargetRange: '0-100',
                appointScoreSign: 0,
                appointUserDDId: '',
                pmTargetId: -1,
                pmDimensionId: -1,
                pmTargetName: '总分',
                pmTargetStand: '',
                pmTargetWeight: pmTargetWeightCount,
                sort: 999,
                score: 0,
                scoreContent: '',
                scoreDesc: '',
                scoreSelfCheckList: coustomScoreSelfCheckList.map(item => {
                  item.score = numRound(item.score, 1)
                  return item
                }),
                leaderCheckList: [],
                appointCheckList: [],
                isMustSelect: 0
              })
            }
            state.pmDataList = pmDataList
            console.log('个人绩效中有数据', res.data, pmDataList)
          }

          closeLoading()
        })
        .catch(err => {
          closeLoading()
        })
    }

    /**组合数据 */
    function combScoreBySelfSubmitParamData(data: CustomPmData[]): ScoreSubmitParamData[] | false {
      console.log(data)

      if (!nowRunning.value || !nowRunning.value.length) return false

      let returnData: ScoreSubmitParamData[] = []

      for (let i = 0; i < data.length; i++) {
        const dimension = data[i]

        for (let ii = 0; ii < dimension.pmTargetList.length; ii++) {
          const target = dimension.pmTargetList[ii]

          if (target.pmDimensionId === -1) continue

          if (target.score === undefined) {
            if (target.isBonus === 1 && nowRunningByLoginuser.value) {
              returnData.push({
                makeUserDDId: loginUser.value.userId,
                makeUserName: loginUser.value.userName,
                pmProgressId: nowRunningByLoginuser.value.pmProgressId,
                pmTargetId: target.pmTargetId,
                score: target.score || 0,
                scoreContent: target.scoreContent,
                scoreDesc: ''
              })
            } else {
              message.warning(
                `维度：${dimension.pmDimensionName}中，指标：${target.pmTargetName}的自评未输入`
              )
              return false
            }
          } else {
            if (target.isBonus === 1 && !checkValueIsInRange(target.score, target.pmTargetRange)) {
              message.warning(
                `维度：${dimension.pmDimensionName}中，加分项：${target.pmTargetName}的自评不在范围内。当前加分项范围为：${target.pmTargetRange}`
              )
              return false
            }
            if (nowRunningByLoginuser.value) {
              returnData.push({
                makeUserDDId: loginUser.value.userId,
                makeUserName: loginUser.value.userName,
                pmProgressId: nowRunningByLoginuser.value.pmProgressId,
                pmTargetId: target.pmTargetId,
                score: target.score || 0,
                scoreContent: target.scoreContent,
                scoreDesc: ''
              })
            }
          }
        }
      }
      return returnData
    }

    /**点击提交时 */
    function handleSubmitClick() {
      handleScoreSummarizeConfirm(state.summarize)
    }

    /**输入总结后确认 */
    function handleScoreSummarizeConfirm(data?: string) {
      let paramData = combScoreBySelfSubmitParamData(state.pmDataList)
      console.log(paramData)

      if (!paramData) return
      if (!scoreLeaderByLoginUser.value && !appointByLoginUser.value) return

      let pmProgressId = scoreLeaderByLoginUser.value
        ? scoreLeaderByLoginUser.value.pmProgressId
        : appointByLoginUser.value
        ? appointByLoginUser.value.pmProgressId
        : undefined

      if (!pmProgressId) return

      console.log(pmProgressId)

      for (let i = 0; i < state.fileList.length; i++) {
        const file = state.fileList[i]
        if (file.status !== 'done') {
          message.warning('文件未上传结束，请等待！')
          return
        }
      }

      startLoading()
      scoreByLeaderSubmit({
        pmProgressId: pmProgressId,
        data: paramData,
        scoreSummary: replaceBreak(data ? data : ''),
        annexData: state.annexDataList
      })
        .then(res => {
          closeLoading()
          router.back()
        })
        .catch(err => {
          closeLoading()
          getPageData()
        })
    }

    /**暂存 */
    function handleTemporarySaveClick() {
      if (!scoreSelfByLoginUser.value) return
      let data = combScoreBySelfSubmitParamData(state.pmDataList)
      if (!data) return
      scoreBySelfTemporarySave({
        pmProgressId: scoreSelfByLoginUser.value.pmProgressId,
        data: data
      })
        .then(res => {
          getPageData()
        })
        .catch(err => {})
    }

    /**获取页面数据 */
    function getPageData() {
      getPmByPmId({
        pmId: Number(defaultPmId),
        updatePm: true,
        success: data => {
          udpateOwner({ownerDDId: data.pmUserDDId})
          setPm(data)
        }
      })

      getPmProgress({
        pmId: defaultPmId,
        updatePmProgress: true,
        success: data => {
          getTableData()
        }
      })
    }

    onMounted(() => {
      getPageData()
    })

    return () => (
      <PMLayout spinning={loading.value}>
        <PMNav>
          <div class='h-full flex items-center'>
            <div class='flex-1 flex items-center'>
              <SplitLine class='mr-16 py-12'></SplitLine>
              <div class='flex-1'>
                {/* owner-msg */}
                {owner.value ? (
                  <span class='flex items-center gap-x-10'>
                    <span class='bg-black rounded-4 overflow-hidden'>
                      {owner.value.avatar ? (
                        <img src={owner.value.avatar || ''} class='w-40 h-40'></img>
                      ) : (
                        <div class='w-40 h-40'>
                          <a-empty></a-empty>
                        </div>
                      )}
                    </span>
                    <span>
                      <CnNormalP class='text-text'>{owner.value.userName}</CnNormalP>
                      <CnNormalP class='text-12'>{owner.value.deptName}</CnNormalP>
                    </span>
                  </span>
                ) : null}
              </div>
            </div>
            <div class='flex items-center gap-x-12'>
              {/* <a-button onClick={handleTemporarySaveClick}>暂存</a-button> */}
              <a-button class=' bg-primary text-white' type='primary' onClick={handleSubmitClick}>
                提交
              </a-button>
            </div>
          </div>
        </PMNav>
        <PMContent>
          <CCard
            title={pm.value?.pmFormName || ''}
            v-slots={{
              title: () => <CnMediumP class='pl-12'>{pm.value?.pmFormName || ''}</CnMediumP>
            }}
            class='px-12 border-0'
          >
            <SplitLine class='w-full h-1 p-0 mb-8'></SplitLine>

            {/* 指标显示区域 */}
            <div class='flex flex-col items-center gap-y-16'>
              {state.pmDataList
                ? state.pmDataList.map((item, dimensionIdx) => (
                    <CCard
                      title={`${item.pmDimensionName}(${item.pmDimensionWeight}%)`}
                      showShadow={false}
                      class='w-full px-12 border-infoLight'
                      style={{
                        background: 'linear-gradient(rgb(236, 245, 255) 0%, rgb(255, 255, 255) 10%)'
                      }}
                      v-slots={{
                        title: () => (
                          <CnMediumP>{`${item.pmDimensionName}(${item.pmDimensionWeight}%)`}</CnMediumP>
                        )
                      }}
                    >
                      <a-table
                        class='custom-table'
                        bordered
                        pagination={false}
                        dataSource={item.pmTargetList}
                        columns={tableColumns.value}
                      >
                        {{
                          bodyCell: ({text, record, column, index}: CBodyCell<CustomPmTarget>) => {
                            switch (column.dataIndex) {
                              case 'score':
                                if (record.sort !== 999) {
                                  return (
                                    <div
                                      class='p-16'
                                      style={{
                                        width: column.width + 'px'
                                      }}
                                    >
                                      <TargetWeight
                                        v-model={[
                                          state.pmDataList[dimensionIdx].pmTargetList[index].score,
                                          'value'
                                        ]}
                                        showUnit={false}
                                        placeholder={
                                          record.isBonus === 1
                                            ? record.pmTargetRange
                                              ? '加分项输入范围：' + record.pmTargetRange
                                              : undefined
                                            : undefined
                                        }
                                      ></TargetWeight>
                                    </div>
                                  )
                                } else {
                                  return <div></div>
                                }

                              case 'scoreContent':
                                if (record.sort !== 999) {
                                  return (
                                    <div class='p-16'>
                                      <a-textarea
                                        value={
                                          state.pmDataList[dimensionIdx].pmTargetList[index]
                                            .scoreContent
                                        }
                                        class=' rounded-4'
                                        rows={1}
                                        onChange={(e: InputEvent) => {
                                          let value = (e.target as HTMLInputElement).value
                                          state.pmDataList[dimensionIdx].pmTargetList[
                                            index
                                          ].scoreContent = value
                                        }}
                                      ></a-textarea>
                                    </div>
                                  )
                                } else {
                                  return <div></div>
                                }

                              default:
                                return (
                                  <CnNormalP
                                    class='p-16 text-12'
                                    style={{
                                      width: column.width + 'px',
                                      whiteSpace: 'break-spaces'
                                    }}
                                  >
                                    {unReplaceBreak(text + '')}
                                  </CnNormalP>
                                )
                            }
                          }
                        }}
                      </a-table>
                    </CCard>
                  ))
                : null}
            </div>
          </CCard>

          <CCard title='主管评分' class='my-16'>
            <a-form-item label='总分'>
              <CnBoldSpan>{scoreCount.value}</CnBoldSpan>
            </a-form-item>
            <a-form-item label='评分总结'>
              <a-textarea v-model={[state.summarize, 'value']} row={3}></a-textarea>
            </a-form-item>
            <a-form-item label='附件'>
              <a-upload
                v-model={[state.fileList, 'file-list']}
                // action={baseUrl + '/dd/ddUploadFile'}
                // name='file'
                multiple={true}
                data={(file: File) => file}
                customRequest={async (e: {data: File; file: {uid: string}}) => {
                  console.log(e)
                  let res = await ddGetAuth({userDDId: loginUser.value.userId}).catch(err => {})
                  if (!res) return
                  let formData = new FormData()
                  formData.append('file', e.data)
                  formData.append('userDDId', loginUser.value.userId)
                  ddUploadFile(formData)
                    .then(res => {
                      let currentFileIdx = state.fileList.findIndex(item => item.uid === e.file.uid)
                      state.fileList[currentFileIdx].status = 'done'
                      state.annexDataList[currentFileIdx] = {
                        annexFileExtension: res.data.dentry.extension,
                        annexFileId: res.data.dentry.id,
                        annexFileName: res.data.dentry.name,
                        annexFileSize: res.data.dentry.size,
                        annexFileSpaceId: res.data.dentry.spaceId
                      }
                      console.log(state.fileList)
                      console.log(state.annexDataList)
                    })
                    .catch(err => {
                      let currentFileIdx = state.fileList.findIndex(item => item.uid === e.file.uid)
                      state.fileList[currentFileIdx].status = 'error'
                      console.log(state.fileList)
                      console.log(state.annexDataList)
                    })
                }}
                onRemove={(file: {uid: string}) => {
                  let currentFileIdx = state.fileList.findIndex(item => item.uid === file.uid)
                  state.annexDataList.splice(currentFileIdx, 1)
                  console.log(state.fileList)
                  console.log(state.annexDataList)
                }}
              >
                <a-button>
                  <i class='iconfont icon-ziliaoshangchuan'></i>
                  上传附件
                </a-button>
              </a-upload>
            </a-form-item>
          </CCard>
        </PMContent>
        {/* <ScoreSummarizeModal
          v-models={[[scoreSummarizeVisible.value, 'visible']]}
          onConfirm={handleScoreSummarizeConfirm}
        ></ScoreSummarizeModal> */}
      </PMLayout>
    )
  }
})
